﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Threading;
using Rabbit.BusinessLogicLayer;
using Rabbit.Model;
using Rabbit.Utils;
namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for Comments.xaml
    /// </summary>
    public partial class Comments : PageBase
    {
        ObservableCollection<Comment> MessagesCollection = new ObservableCollection<Comment>();
        List<Comment> MessagesPool = new List<Comment>();

        CommentsBL commentsBL;

        public Comments()
        {
            InitializeComponent();

            lstMyCommentList.ItemsSource = MessagesCollection;

            commentsBL = new CommentsBL(MySettings.UpdateInterval.Value);
            commentsBL.OnMessageInitialized = CommentsInitialized;
            commentsBL.OnUnknownExceptionOccured = base.OnUnHandledExceptionOccured;
            commentsBL.OnPublishAPICallTooFrequent = base.OnCallAPITooFrequentExceptionOccured;
            commentsBL.OnNewMessageReceived = NewCommentsReceived;
            BeginInitializeMessage();
        }

       

        void CommentsInitialized(List<Comment> commentList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                commentList.ForEach(c => MessagesCollection.Add(c));
            }), DispatcherPriority.Background);

            //IsMessageInitialized = true;
            //ShowSuccessfulMessage("加载成功");
        }
        void NewCommentsReceived(List<Comment> commentList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (commentList.Count==0)
                    {
                        return;
                    }


                    MessagesCollection.ForEach(m => m.CreatedAt = m.CreatedAt);//refresh the create time on UI
                    MessagesPool.InsertRange(0, commentList);//move the comment list to the queue
                      
                    TryPopupMessage<Comment>(MySettings.PopupForNewComment,
                        new Action<object, MouseButtonEventArgs>((o, args) =>
                        {
                            this.Dispatcher.BeginInvoke((Action)delegate()
                            {
                                (App.Current.MainWindow as MainWindow).FlushMyCommentStatusPool(o, args);
                            });
                        }),
                        MessagesPool.Count,
                        "评论",
                        commentList[0]);
                }),
                DispatcherPriority.Background);
        }

        protected override void NotifyMainWindowNewMessageCountChanged(int messageCount)
        {
            (App.Current.MainWindow as MainWindow).NewCommentsCount = messageCount;
        }

        public override void DoWork(object obj = null)
        {
            App.StopTwinkleSysTrayIcon();

            MessagesCollection.InsertRange<Comment>(MessagesPool, MaxRecordsCountShowed);
            lstMyCommentList.ScrollIntoView(MessagesCollection[0]);
            MessagesPool.Clear();
            NotifyMainWindowNewMessageCountChanged(0);
        }

        public override void BeginInitializeMessage()
        {
            commentsBL.StartFetchingMessage();
        }

        public override void pager_OnFirstPageClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Comment> fetchedMessage = commentsBL.GetFirstPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = commentsBL.CanGetPreviousePage;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnPreviousePage(object sender, System.Windows.RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Comment> fetchedMessage = commentsBL.GetPreviousePageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = commentsBL.CanGetPreviousePage;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public  override void pager_OnNextPageClick(object sender, System.Windows.RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Comment> fetchedMessage = commentsBL.GetNextPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = true;
                        pager.CanNextPageClick = fetchedMessage.Count > 0;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }
    }
}
